package gw.com.android.ui.home;

import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gwtsz.gts2.hx.R;

import java.util.List;
import java.util.Locale;

import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigType;
import gw.com.android.presenter.http.HttpCallback;
import gw.com.android.presenter.http.TopNewsRequest;
import gw.com.android.ui.news.TopNewsAdapter;
import gw.com.android.utils.PackStatis;
import www.com.library.model.DataItemDetail;
import www.com.library.view.XRecyclerView;

/**
 * @author jett
 * @since 2018-11-08.
 */
class HomeTopnewsPresenter {

    private final Activity mActivity;
    private final TextView tvTips;
    private final LinearLayout llEmpty;
    private final XRecyclerView rvList;

    private boolean loadSuccess = false;
    private TopNewsRequest topNewsRequest = new TopNewsRequest();
    private TopNewsAdapter mAdapter;

    HomeTopnewsPresenter(Activity activity, View topnewsView) {
        this.mActivity = activity;
        tvTips = topnewsView.findViewById(R.id.topnews_tips);
        llEmpty = topnewsView.findViewById(R.id.topnews_empty);
        rvList = topnewsView.findViewById(R.id.topnews_list);
        rvList.setRefreshFrozen(true);
        init();
    }

    private void init() {
        rvList.setScrollFrozen(true);
        rvList.setLayoutManager(new LinearLayoutManager(mActivity));
        rvList.setAdapter(new EmptyAdapter());
        rvList.hideFooter();
        rvList.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                requestData();
            }

            @Override
            public void onLoadMore() {
                nextPage();
            }
        });

        List<TopNewsRequest.TopNewsData> list = topNewsRequest.fetchLocal();
        refreshUi(list, true);
        rvList.setRefreshing(true);
    }

    private TopNewsAdapter initAdapter() {
        final List<String> marks = GTConfig.instance().getTopNewsMark();
        TopNewsAdapter adapter = new TopNewsAdapter(mActivity, marks);
        adapter.setOnItemClickListener(new TopNewsAdapter.OnItemClickListener() {
            @Override
            public void OnItemClicked(RecyclerView.Adapter adapter, View view, int position) {
                TopNewsRequest.TopNewsData item = mAdapter.getItem(position);
                if (item != null) {
                    PackStatis.getToService("clickFnews", "Fnews", null, null);
                    item.pviews++;
//                    topNewsRequest.addPreview(item.id);//这里不用调用阅读数+1，因为H5页面内部会自动+1
                    if (!mAdapter.marked(item.id)) {
                        if (position < 20) {
                            GTConfig.instance().addTopNewsMark(item.id);
                        }
                        mAdapter.addMark(item.id);
                    }
                    mAdapter.notifyChangeDelay();
                    //H5的方式展示详情
                    //String url = ConfigUtil.instance().getUrlPath("topNewsDetailH5") + item.id + ".html";
                    String url = "https://app.ftww.com/ft/article.html?id=" + item.id;
                    DataItemDetail detail = new DataItemDetail();
                    detail.setStringValue(ConfigType.CONFIG_TYPE_TYPE_URL_TAG, url);
                    detail.setStringValue(ConfigType.CONFIG_TYPE_TITLE_TAG, mActivity.getString(R.string.home_trade_news_topnews));
                    ActivityManager.showWebPageActivity(mActivity, detail, null);
                }
            }
        });
        return adapter;
    }

    public void onSelected() {
        if (!loadSuccess) {
            requestData();
        }
    }

    public void onRefresh() {
        rvList.smoothScrollToPosition(0);
        rvList.setRefreshing(true);
    }

    public void setFrozen(boolean frozen) {
        rvList.setScrollFrozen(frozen);
    }

    private void requestData() {
        topNewsRequest.call(new HttpCallback<List<TopNewsRequest.TopNewsData>>() {
            @Override
            public void onSuccess(List<TopNewsRequest.TopNewsData> result) {
                rvList.refreshComplete();
                showTips(result);
                refreshUi(result, false);
            }

            @Override
            public void onFailure(Exception e) {
                rvList.refreshComplete();
                refreshUi(null, false);
            }
        });
    }

    private void nextPage() {
        topNewsRequest.nextPage(new HttpCallback<List<TopNewsRequest.TopNewsData>>() {
            @Override
            public void onSuccess(List<TopNewsRequest.TopNewsData> result) {
                rvList.loadMoreComplete();
                rvList.setNoMore(!topNewsRequest.hasNextPage());
                appendUi(result);
            }

            @Override
            public void onFailure(Exception e) {
                rvList.loadMoreComplete();
            }
        });
    }

    private void refreshUi(List<TopNewsRequest.TopNewsData> list, boolean isCache) {
        if (list == null || list.isEmpty()) {
            if (!loadSuccess && !isCache) {
                rvList.setVisibility(View.GONE);
                llEmpty.setVisibility(View.VISIBLE);
            }
            return;
        }
        if (!loadSuccess) {
            loadSuccess = true;
            llEmpty.setVisibility(View.GONE);
            rvList.setVisibility(View.VISIBLE);
        }
        if (mAdapter == null) {
            mAdapter = initAdapter();
            rvList.setAdapter(mAdapter);
        }
        mAdapter.updateData(list);
        rvList.setNoMore(!topNewsRequest.hasNextPage());
    }

    private void appendUi(List<TopNewsRequest.TopNewsData> list) {
        if (mAdapter == null || list == null || list.isEmpty()) {
            return;
        }
        mAdapter.appendData(list);
    }

    private void showTips(List<TopNewsRequest.TopNewsData> list) {
        if (list == null || list.isEmpty()) {
            return;
        }

        List<String> ids = mAdapter == null ? null : mAdapter.getNewsIds();
        if (ids == null || ids.isEmpty()) {
            showTips(list.size());
            return;
        }
        int count = 0;
        for (TopNewsRequest.TopNewsData data : list) {
            if (!ids.contains(data.id)) {
                count++;
            }
        }
        if (count > 0) {
            showTips(count);
        }
    }

    private void showTips(int count) {
        String text = String.format(Locale.getDefault(), mActivity.getString(R.string.home_trade_news_update_count), count);
        tvTips.setText(text);
        tvTips.setVisibility(View.VISIBLE);
        tvTips.clearAnimation();
        TranslateAnimation tranAnim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1, Animation.RELATIVE_TO_SELF, 0);
        AlphaAnimation alphaAnim = new AlphaAnimation(0, 1);
        AnimationSet animSet = new AnimationSet(true);
        animSet.addAnimation(tranAnim);
        animSet.addAnimation(alphaAnim);
        animSet.setDuration(200);
        tvTips.startAnimation(animSet);
        hideTipsDelay();
    }

    private void hideTipsDelay() {
        Runnable animTask = new Runnable() {
            @Override
            public void run() {
                hideTips();
            }
        };
        AppMain.getApp().getHandler().postDelayed(animTask, 1000);
    }

    private void hideTips() {
        TranslateAnimation tranAnim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1);
        AlphaAnimation alphaAnim = new AlphaAnimation(1, 0);
        AnimationSet animSet = new AnimationSet(true);
        animSet.addAnimation(tranAnim);
        animSet.addAnimation(alphaAnim);
        animSet.setDuration(200);
        animSet.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                tvTips.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        animSet.setFillAfter(true);
        tvTips.startAnimation(animSet);
    }

    private class EmptyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_topnews_stub, parent, false);
            return new RecyclerView.ViewHolder(view) {
            };
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        }

        @Override
        public int getItemCount() {
            return 5;
        }

    }

}
